package com.j1ay.forum.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j1ay.forum.dao.mapper.AnswerMapper;
import com.j1ay.forum.dao.mapper.QuestionMapper;
import com.j1ay.forum.model.dto.params.AgreeParams;
import com.j1ay.forum.model.pojo.po.Answer;
import com.j1ay.forum.model.pojo.po.Question;
import com.j1ay.forum.model.dto.params.PageParams;
import com.j1ay.forum.model.dto.params.QuestionParam;
import com.j1ay.forum.service.QuestionService;
import com.j1ay.forum.service.ThreadService;
import com.j1ay.forum.service.TypeService;
import com.j1ay.forum.service.UserService;
import com.j1ay.forum.model.pojo.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author J1ay
 * @Date 2021/12/14 21:44
 * @Description
 */

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired(required = false)
    private QuestionMapper questionMapper;

    @Autowired(required = false)
    private AnswerMapper answerMapper;

    @Autowired
    private TypeService typeService;

    @Autowired
    private UserService userService;

    @Autowired
    private ThreadService threadService;

    private static final int isStatus = 1;

    @Override
    public Result listQuestion(PageParams pageParams) {
        Page<Question> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        // 先按置顶排序，再按创建的时间倒序排序
        queryWrapper.eq(Question::getStatus, isStatus);
        queryWrapper.orderByDesc(Question::getZhiding, Question::getCreateTime);
        Page<Question> questionPage = questionMapper.selectPage(page, queryWrapper);
        List<Question> records = questionPage.getRecords();
        List<QuestionVo> questionVoList = copyList(records, true, true);

        PageResult<QuestionVo> result = new PageResult();
        result.setCurrentPage(questionPage.getCurrent());
        result.setPageSize(questionPage.getSize());
        result.setList(questionVoList);
        result.setTotals(questionPage.getTotal());

        return Result.success(result);
    }

    // 类型转换
    private List<QuestionVo> copyList(List<Question> records,boolean isType,boolean isAuthor) {
        List<QuestionVo> questionVoList = new ArrayList<>();
        for (Question record: records) {
            questionVoList.add(copy(record, isType, isAuthor));
        }
        return questionVoList;
    }

    private QuestionVo copy(Question question,boolean isType,boolean isAuthor) {
        QuestionVo questionVo = new QuestionVo();
        BeanUtils.copyProperties(question, questionVo);
        questionVo.setCreateTime(new DateTime(question.getCreateTime()).toString("yyyy-MM-dd HH:mm"));
        questionVo.setUpdateTime(new DateTime(question.getUpdateTime()).toString("yyyy-MM-dd HH:mm"));
        if(isType){
            Long typeId = question.getTypeId();
            System.out.println(typeId);
            questionVo.setType(typeService.findTypeByTypeId(typeId));
        }
        if (isAuthor) {
            //拿到作者id
            String username = question.getUsername();
            System.out.println(username);
            questionVo.setAuthorName(userService.findUserById(username).getNickname());
        }
        return questionVo;
    }


    @Override
    public Result hotQuestion(int limit) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Question::getStatus, isStatus)
                .orderByDesc(Question::getViewCount)
                .select()
                .last("limit " + limit);
        List<Question> questionList = questionMapper.selectList(queryWrapper);

        return Result.success(copyList(questionList, true, true));
    }

    @Override
    public Result newQuestion(int limit) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper
                .eq(Question::getStatus, isStatus)
                .orderByDesc(Question::getCreateTime)
                .select()
                .last("limit " + limit);
        List<Question> questionList = questionMapper.selectList(queryWrapper);

        return Result.success(copyList(questionList, true, true));
    }

    @Override
    public Result getUserQuestion(String username) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Question> queryWrapper1 = new LambdaQueryWrapper<>();

        queryWrapper
                .eq(Question::getStatus, isStatus)
                .eq(Question::getUsername, username)
                .orderByDesc(Question::getCreateTime)
                .select();
        queryWrapper1
                .eq(Question::getStatus, 0)
                .eq(Question::getUsername, username)
                .orderByDesc(Question::getCreateTime)
                .select();
        List<Question> questionList = questionMapper.selectList(queryWrapper);
        List<Question> questionList1 = questionMapper.selectList(queryWrapper1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("public", copyList(questionList, true, true));
        jsonObject.put("check", copyList(questionList1, true, true));
        return Result.success(jsonObject);
    }

    @Override
    public Result findQuestionById(Long questionId) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Question::getId, questionId)
                .select()
                .last("limit 1");
        Question question = questionMapper.selectOne(queryWrapper);
        QuestionVo questionVo = copy(question, true, true);
        // 将更新阅读量的操作放到线程池里去

        threadService.updateViewCount(questionMapper, question);
        return Result.success(questionVo);
    }


    /**
     * 根据id返回问题详情（回帖）
     * @param questionId
     * @return
     */
    @Override
    public QuestionVo findQuestionVoById(Long questionId) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Question::getId, questionId)
                .select()
                .last("limit 1");
        Question question = questionMapper.selectOne(queryWrapper);
        QuestionVo questionVo = copy(question, true, true);
        return questionVo;
    }

    @Override
    public Result addQuestion(QuestionParam questionParam) {

        String title = questionParam.getTitle();
        String content = questionParam.getContent();
        String username = questionParam.getUsername();
        Long typeId = questionParam.getTypeId();

        if (null == typeId || StringUtils.isBlank(title) ||
        StringUtils.isBlank(content) || StringUtils.isBlank(username)) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }

        Question question = new Question();
        question.setTitle(title);
        question.setTypeId(typeId);
        question.setContent(content);
        question.setUsername(username);
        question.setCreateTime(new Date());

        int res = this.questionMapper.insert(question);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }


    @Override
    public Result delete(Long id) {
        if (null == id) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        this.questionMapper.deleteById(id);
        return Result.success(null);
    }


    @Override
    public Result findQuestionByType(Long typeId, PageParams pageParams) {
        Page<Question> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        // 先按置顶排序，再按创建的时间倒序排序
        queryWrapper
                .eq(Question::getStatus, isStatus)
                .eq(Question::getTypeId, typeId);
        queryWrapper.orderByDesc(Question::getZhiding, Question::getCreateTime);
        Page<Question> questionPage = questionMapper.selectPage(page, queryWrapper);
        List<Question> records = questionPage.getRecords();
        List<QuestionVo> questionVoList = copyList(records, true, true);

        PageResult<QuestionVo> result = new PageResult();
        result.setCurrentPage(questionPage.getCurrent());
        result.setPageSize(questionPage.getSize());
        result.setList(questionVoList);
        result.setTotals(questionPage.getTotal());

        return Result.success(result);
    }


    /**
     * 点赞该问题
     * @param questionId
     * @return
     */
    @Override
    public Result toPraiseQuestion(Long questionId) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Question::getId, questionId)
                .select()
                .last("limit 1");
        Question question = questionMapper.selectOne(queryWrapper);
        // 放入线程池，进行点赞操作
        threadService.updatePraise(questionMapper, question);
        return Result.success(null);
    }


    /**
     * 该问题采纳该回答
     * @param agreeParams
     * @return
     */
    @Override
    public Result toAgreeAnswer(AgreeParams agreeParams) {
        Long questionId = agreeParams.getQuestionId();
        Long agreeId = agreeParams.getAgreeId();
        if (Objects.isNull(questionId) || Objects.isNull(agreeId)) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        LambdaQueryWrapper<Answer> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1
                .eq(Answer::getId, agreeId)
                .select()
                .last("limit 1");
        Answer answer = answerMapper.selectOne(queryWrapper1);
        if (Objects.isNull(answer)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), "不存在该回答哦~");
        }

        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Question::getId, questionId)
                .select()
                .last("limit 1");
        Question question = questionMapper.selectOne(queryWrapper);
        question.setAgreeId(agreeId);
        int res  = questionMapper.update(question, queryWrapper);
        if (res == 0) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }

        return Result.success(null);
    }
}
